package com.baseDemo.web.service.quartz.impl;

import java.util.List;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import com.baseDemo.web.dao.quartz.QuartzEntityDao;
import com.baseDemo.web.entity.QuartzEntity;
import com.baseDemo.web.service.quartz.QuartzService;
import com.share.hibernate.baseDaoSupport.PageUtil;
import com.share.quartz.service.QuartzJobService;
import com.share.service.baseServiceSupport.impl.BaseServiceSupport;

@Service
public class QuartzServiceImpl extends BaseServiceSupport<QuartzEntity> implements QuartzService{
	private Logger logger = Logger.getLogger(getClass());
	@Resource QuartzJobService quartzJobService;
	@Resource QuartzEntityDao quartzEntityDao;
	@Resource PageUtil pageUtil;
	@Override
	public PageUtil getListForPageToJson(Integer start, Integer limit) {
		Integer rowTotal = quartzEntityDao.getPageTotal();
		pageUtil.setTotal(rowTotal);
		List<QuartzEntity> list = quartzEntityDao.find(limit, start);
		pageUtil.setEntityList(list);
		return pageUtil;
	}
	@Override
	public String startQuartzCron(QuartzEntity quartzEntity) {
		 try {
			quartzJobService.addNewJob(quartzEntity);
			quartzEntity.setStatus("启动");
			quartzEntityDao.update(quartzEntity);
			return  String.valueOf(1);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return  String.valueOf(0);
		}
	}
	@Override
	public String pauseQuartzCron(QuartzEntity quartzEntity) {
		try {
			quartzJobService.pauseJob(quartzEntity);
			quartzEntity.setStatus("暂停");
			quartzEntityDao.update(quartzEntity);
			return String.valueOf(1);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return  String.valueOf(0);
		}
	}
	@Override
	public String stopQuartzCron(QuartzEntity quartzEntity) {
		try {
			quartzJobService.deleteJob(quartzEntity);
			quartzEntity.setStatus("停止");
			quartzEntityDao.update(quartzEntity);
			return String.valueOf(1);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return  String.valueOf(0);
		}
	}
	public void init() { 
		logger.info("---定时任务service启动-----");
		List<QuartzEntity> list = quartzEntityDao.findStartQuartz();
		if(list!=null&&list.size()>0){
			for (QuartzEntity quartzEntity : list) {
				this.startQuartzCron(quartzEntity);
				logger.info("--启动定时任务--"+quartzEntity.getDescription());
			}
		}
	} 
	@PreDestroy
	public void destory() { 
		logger.info("---定时任务service销毁-----");
	} 
}
